<?php
/**
 * 系统操作
 */
class controller_system extends controller_base {

	/**
	 * backup
	 */
	public function action_backup() {
		$model_backup = new model_backup();
		$this->assign('logs', $model_backup->get_logs());
	}
	
	/**
	 * backup do
	 */
	public function action_backup_do() {
		$type = empty($_GET['type']) ? 'all' : $_GET['type'];

		$model_backup = new model_backup();

		switch ($type) {
			//记事备份
			case 'notes':
				$model_backup->make_sql_text(array(DB_PREFIX.'notes'));
				break;
			
			//账务备份
			case 'finance':
				$model_backup->make_sql_text(array(DB_PREFIX.'payout', DB_PREFIX.'audit', DB_PREFIX.'income', DB_PREFIX.'category'));
				break;
			
			//日志备份
			case 'logs':
				$model_backup->make_sql_text(array(DB_PREFIX.'logs'));
				break;
				
			//近3天日志备份
			case 'logs_recent':
				$time_recent = strtotime(date('Y-m-d')) - 86400*3;
				$model_backup->make_sql_text(array(DB_PREFIX.'logs'), "WHERE create_time >= '$time_recent'");
				break;

			//当日记事+日志备份
			case 'today':
				$today = time() - 86400;
				$model_backup->make_sql_text(array(DB_PREFIX.'logs', DB_PREFIX.'notes'), "WHERE create_time >= '$today'");
				break;
			
			//完全备份
			case 'all':
				$model_backup->make_sql_text(array());
				break;
			
			default:
				break;
		}
		
        $start = microtime(1);
        require ROOT.'/library/pclzip/pclzip.lib.php';
        require ROOT.'/library/phpmailer/class.phpmailer.php';

        //文件名
        $sql_file = ROOT.'/cache/fmsbackup_'.(date('Ymh_His_').rand(1000, 9999).'.sql');
        $zip_file = $sql_file.'.zip';

        //SQL原文件
        $sql = $model_backup->get_sql_text();
        file_put_contents($sql_file, $sql);

        //压缩
        $zip = new PclZip($zip_file);
        $zip->create($sql_file, PCLZIP_OPT_REMOVE_ALL_PATH);

        //邮件信息
        $time = date('Y-m-d H:i:s');
        $sql_size = round(filesize($sql_file) / 1024, 2);
        $zip_size = round(filesize($zip_file) / 1024, 2);
        $cost_time = round(microtime(true) - $start, 3);

        //$body_template
        eval('$body_template = "'.Config::get('MAIL_FOR_BACKUP_TEMPLATE').'";');

        //收发邮件人
        $mail_from = array();
        parse_str(str_replace("\r\n", '&', Config::get('MAIL_FOR_BACKUP_FROM_INFO')), $mail_from);
        $mail_to = preg_split('/\s+/', Config::get('MAIL_FOR_BACKUP_TO'));

        //发送邮件
        $mail = new PHPMailer();
        $mail->IsSMTP(); // send via SMTP
        $mail->Host = $mail_from['smtp']; // SMTP servers
        $mail->SMTPAuth = true; // turn on SMTP authentication
        $mail->Username = $mail_from['fullname']; // SMTP username
        $mail->Password = $mail_from['password']; // SMTP password
        $mail->From = $mail_from['fullname'];
        $mail->FromName = $mail_from['showname'];
        foreach ($mail_to as $item)
        {
            $mail->AddAddress($item, '');
        }
        $mail->WordWrap = 50; // set word wrap
        $mail->AddAttachment($zip_file, 'fbk_'.date('ymd_His').'.zip'); // attachment
        $mail->IsHTML(true); // send as HTML
        $mail->CharSet = 'UTF-8';
        $mail->Subject = "[{$_SERVER['HTTP_HOST']}]".date('Y-m-d H:i ').'FMS Backup '.ucfirst($type);
        $mail->Body = $body_template;
        $mail->AltBody = 'FMS Mailer';

        if ($mail->Send())
        {
            $cost_time = round(microtime(true) - $start, 3);
            new model_logs("$type - Cost $cost_time ms - $zip_size kb - {$_SERVER['HTTP_USER_AGENT']}");
        }
        else
        {
            new model_logs("备份邮件发送失败！- {$mail->ErrorInfo} - $type - $zip_size kb  - {$_SERVER['HTTP_USER_AGENT']}");
        }

        //删除文件
        unlink($sql_file);
        unlink($zip_file);

		$this->message('备份完成', '?m=system&a=backup');
	}
	
	/**
	 * 工具 - 生成sql文件
	 */
	public function action_makesql() {
		!file_exists(ROOT.'/a.txt') && exit('ERROR - 根目录下无a.txt');
		$res = file_get_contents(ROOT.'/a.txt');
		
		$res = str_replace('[START]', '', $res);
		$res = str_replace('[END]', '', $res);
		$res = base64_decode($res);
		
		file_put_contents(ROOT.'/a.sql', $res);
		exit('SUCCESS - '.round(microtime(true) - TIME_START_ACTION, 3).'ms');
	}
	
	/**
	 * 工具 - 404日志分析
	 */
	public function action_404() {
		// 整理源数据
		$data = array();
		$date = empty($_GET['date']) ? date('Y-m-d') : $_GET['date'];
		$res = file_get_contents('../log_404/'.$date.'.txt');
		$res_arr = explode("\n", $res);
		foreach ($res_arr as $row) {
			$data[] = explode("\t", $row);
		}
		array_pop($data);
		
		// IP分析
		$ip = array();
		$ip_data = array();
		foreach ($data as $row) {
			isset($ip[$row[1]]) ? $ip[$row[1]]++ : $ip[$row[1]] = 1;
			$ip_data[$row[1]] = $row;
		}
		arsort($ip);
		
		// 时间分析
		$time_res = array();
		$time_data = array();
		foreach ($data as $row) {
			$key = date('H:i', strtotime($row[0]));
			isset($time_res[$key]) ? $time_res[$key]++ : $time_res[$key] = 1;
		}
		$time_start = strtotime($date);
		$time_end = $time_start + 86400 - 1;
		for($i = $time_start; $i < $time_end; $i += 60) {
			$key = date('H:i', $i);
			$time_data[$key] = isset($time_res[$key]) ? $time_res[$key] : 0;
		}
		
		// 输出
		$output = '';
		$output = '<style>body { font-size:12px; }</style>';
		$output .= $date.' COUNT:<b>'.count($data).'</b> IP:<b>'.count($ip).'</b>';
		$output .= '<hr><b>Time</b><br>';		
		foreach ($time_data as $key => $row) {
			$output .= $key.' =》 <span title="'.$row.'">'.str_repeat('=', $row).'</span><br />';
		}
		$output .= '<hr><b>IP</b><br>';
		/*foreach ($ip as $key => $row) {
			$output .= $key.' =》'.$row.'<br />';
		}*/
		
		header('Content-type:text/html;charset=utf-8');
		echo $output;
	}
	
	/**
	 * 程序点击排行
	 */
	public function action_app_hits() {
		$model_app_hits = new model_app_hits();
		$res = $model_app_hits->find_all('1', 'hits DESC');
		
		$this->assign('res', $res);
	}
	
	/**
	 * 登录日志
	 */
	public function action_login_logs() {
		$model_logs = new model_logs();
		$res = $model_logs->find_all("model='auth' AND action='login_do'", 'create_time DESC', 10);

		$this->assign('res', $res);
	}
}
?>
